package com.zxjbyte.yiyi.framework.oss.config;

import cn.hutool.core.annotation.AnnotationUtil;
import com.zxjbyte.yiyi.framework.oss.enums.OssStorageEnum;
import com.zxjbyte.yiyi.framework.oss.storage.OssConfig;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.validation.constraints.NotBlank;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * oss储器器主配置
 * 优先级读取yaml中配置，如果yaml中没有配置则读取db配置中的主配置为项目oss配置
 * @Author zhangxingjia
 * @Date 2023/5/9 11:03
 * @Version: 1.0
 */
@Getter
@Setter
@ConfigurationProperties(prefix = OssProperties.OSS_PROP_PREFIX)
public class OssProperties implements SmartInitializingSingleton {

    public static final String OSS_PROP_PREFIX = "yiyi.oss";

    /**
     * 是否启用
     */
    private Boolean enabled = false;

    /**
     * 是否开启上传记录日志
     */
    private Boolean needRecord = true;

    /**
     * 是否开启租户模式
     */
    private Boolean tenantMode = false;

    /**
     * 存储器
     */
    private OssStorageEnum storage = OssStorageEnum.S3;

    /**
     * 存储器配置
     */
    private Map<String, Object> config = new LinkedHashMap<>();


    @Override
    public void afterSingletonsInstantiated() {
        if(!enabled){
            return;
        }
        if(!config.isEmpty()){
            Class<? extends OssConfig> configClass = storage.getConfigClass();
            Field[] fields = configClass.getDeclaredFields();
            for(Field field : fields){
                String fieldName = field.getName();
                NotBlank annotation = AnnotationUtil.getAnnotation(field, NotBlank.class);
                if(annotation != null && !config.containsKey(fieldName)) {
                    throw new IllegalArgumentException("[" + OSS_PROP_PREFIX + ".config] configuration error, " +
                            "Missing configuration for field [" + fieldName + "]");
                }
            }
        }
    }
}
